package edu.cmu.atlub.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import edu.cmu.atlub.persistence.ConnectionManager;

public class SusModel {

    public static void insertUser(long userId) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
	Connection conn = ConnectionManager.getConnection();
	insertUser(userId, conn);
	conn.close();
    }
    
    public static void insertUser(long userId, Connection conn) throws SQLException {
	String sqlStr = "INSERT IGNORE INTO sus (user_id) VALUES (?);";
	PreparedStatement stmt = conn.prepareStatement(sqlStr);
	stmt.setLong(1, userId);
	stmt.executeUpdate();
    }
    
    public static long[] getAllUserIds(boolean includeProcessed) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
	Connection conn = ConnectionManager.getConnection();
	long[] result = getAllUserIds(conn, includeProcessed);
	conn.close();
	return result;
    }
    
    public static long[] getAllUserIds(Connection conn, boolean includeProcessed) throws SQLException {
	String sqlStr = null; 
	
	if (includeProcessed) {
	    sqlStr = "SELECT user_id FROM sus WHERE user_id NOT IN (SELECT user_id FROM do_not_use_sus);";
	} else {
	    sqlStr = "SELECT user_id FROM sus WHERE user_id NOT IN (SELECT user_id FROM processed_sus) AND user_id NOT IN (SELECT user_id FROM do_not_use_sus);";
	}
	PreparedStatement stmt = conn.prepareStatement(sqlStr);
	ResultSet resultSet = stmt.executeQuery(sqlStr);
	
	ArrayList<Long> userIdList = new ArrayList<Long>();
	
	while (resultSet.next()) {
	    long userId = resultSet.getLong("user_id");
	    userIdList.add(userId);
	}
	
	long[] result = new long[userIdList.size()];
	for (int i = 0; i < userIdList.size(); i++) {
	    result[i] = userIdList.get(i);
	}
	
	return result;
    }
    
    /**
     * @param args
     * @throws SQLException 
     * @throws ClassNotFoundException 
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     */
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
	long[] allUserIds = getAllUserIds(true);
	for (int i = 0; i < allUserIds.length; i++) {
	    System.out.printf("%d\n", allUserIds[i]);
	}
	
	System.err.printf("total number of users: %d\n", allUserIds.length);
    }

}
